from PIL.Image import Image
from cnocr import CnOcr
import threading
import sys
from pathlib import Path

if getattr(sys, 'frozen', False):
    base_path = Path(sys.executable).parent
else:
    base_path = Path(__file__).parent.parent

print(f"exe 当前路径: {base_path}")
model_path = base_path / 'models/densenet/cnocr-v2.3-densenet_lite_136-gru-epoch=004-ft-model.onnx'
det_model_dir = base_path / 'models/det/ch_PP-OCRv3_det_infer.onnx'
rec_vocab_fp = base_path / 'models/label_cn.txt'
ocr = CnOcr(
    rec_model_fp=model_path,
    det_model_fp=det_model_dir,
    rec_vocab_fp=rec_vocab_fp
)
lock = threading.Lock()


def ocr_image(img):
    try:
        res = ocr.ocr(img)
        return {
            'state': True,
            'data': res
        }
    except Exception as e:
        return {
            'state': False,
            'data': '错误:{}'.format(e)
        }


def ocr_image_rect(img:Image, left:int,top:int,right:int,bottom:int):
    try:
        img =img.crop((left,top,right,bottom))
        res = ocr.ocr(img)
        return {
            'state': True,
            'data': res
        }
    except Exception as e:
        return {
            'state': False,
            'data': '错误:{}'.format(e)
        }
